package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.dto.UserDTO;
import com.leyou.exception.LyException;
import com.leyou.user.UserClient;
import com.leyou.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constants.JwtConstants.KEY_PREFIX;

/**
 * @author ：qcq
 * @date ：Created in 2020/12/18 15:38
 * @description：
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        UserDTO userDTO = userClient.queryUsernameAndPassword(username, password);
        if (userDTO == null) {
            throw new LyException(400, "用户名或密码错误");
        }
        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());

        String token = jwtUtils.createJwt(userDetail);
        Cookie cookie = new Cookie("LY_TOKEN", token);
        cookie.setDomain("leyou.com");
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(token);
            UserDetail userDetail = payload.getUserDetail();
            String key = KEY_PREFIX + userDetail.getUsername();
            this.redisTemplate.delete(key);
        } catch (Exception e) {
        }

        //重新生成cookie，覆盖之前的
        Cookie cookie = new Cookie(COOKIE_NAME,"");
        cookie.setDomain("leyou.com");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
